package com.example.demo.service.impl;

import com.example.demo.service.IUserService;
import com.example.demo.vo.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 用户
 */
@Service
public class UserService implements IUserService {

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired
    JavaMailSender mailSender;

    /**
     * 发送普通纯文本邮件
     */
    @Override
    public void sendEmail01(Email email) {
        String mail = email.getEmails()[0];
        StringBuffer stringBuffer = new StringBuffer();
        for (int x = 0; x <= 5; x++) {
            int random = (int) (Math.random() * (9 - 1 + 1)) + 1; // 生成[1,9]的随机数
            stringBuffer.append(random);
        }
        String string = stringBuffer.toString();
        // 给验证码赋值
        int i = Integer.parseInt(string);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 标题
        simpleMailMessage.setSubject(email.getTitle());
        // 内容
        simpleMailMessage.setText("快完成了,@" + mail + "！\n为了保护您的 A子辰 帐户，" +
                "我们只需要验证您的电子邮件地址：" + mail + "\n这将让您从 A子辰 接收通知和密码重置。\n" +
                "您的验证码是：" + i + "\n您收到这封电子邮件是因为您最近创建了一个" +
                "新的 A子辰 帐户或添加了一个新的电子邮件地址。如果这不是您，请忽略此电子邮件。");
        // 发件人邮箱
        simpleMailMessage.setFrom(fromEmail);
        // 收件人邮箱
        simpleMailMessage.setTo(mail);
        mailSender.send(simpleMailMessage);
    }
}
